<?php
/**
 * 支付宝支付处理类
 */

namespace App\Services\Tools;

use Alipay\EasySDK\Kernel\CertEnvironment;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;

// Todo 待修复
class AliPayService
{

    private $id;
    /**
     * 初始化参数
     *
     * @param array $options
     * @param $options ['appId']  应用ID，在支付宝上获取
     * @param $options ['rsaPrivateKey'] 应用密钥，与应用公钥一组，公钥填写到支付宝
     * @param $options ['signType'] 签名方式
     * @param $options ['alipayrsaPublicKey'] 支付宝公钥，在支付宝上获取
     * @param $options ['notifyUrl'] 支付宝回调地址
     * @param $options ['returnUrl'] 用于web支付返回地址
     */
    public function __construct(array $params,$id)
    {
        $this->id = $id;
        $aliConfig = new Config();
        $aliConfig->protocol = $params['protocol'];
        $aliConfig->gatewayHost = $params['gatewayHost'];
        $aliConfig->signType = $params['signType'];
        $aliConfig->appId = $params['appId'];
        $aliConfig->merchantPrivateKey = $params['merchantPrivateKey'];
        $aliConfig->alipayPublicKey = $params['alipayPublicKey'];
        $aliConfig->notifyUrl = $params['notifyUrl'];
        $aliConfig->encryptKey = $params['encryptKey'];
        if(!empty($params["alipayCertPath"])){
            $aliConfig->merchantCertPath = $params["merchantCertPath"];
            $aliConfig->alipayCertPath = $params["alipayCertPath"];
            $aliConfig->alipayRootCertPath = $params["alipayRootCertPath"];
        }

        Factory::setOptions($aliConfig);
    }


    //支付宝 h5支付
    public function AliPayH5($order_number, $money, $title, $returnUrl): string
    {
//        $host = app('request')->header('REQUEST_SCHEME') . '://' .app('request')->header('SERVER_NAME') ;
        $result = Factory::payment()
            ->wap()
            ->optional('passback_params','h5_'.$this->id)
            ->pay($title, $order_number, $money, $returnUrl, $returnUrl);

        return base64_encode($result->body);
    }

    /**
     * 支付宝app支付 需要签约 APP支付
     * @param array $data 业务参数 body subject out_trade_no total_amount
     * @param string $data ['out_trade_no'] 订单号  必填
     * @param string $data ['total_amount'] 订单金额  必填
     * @param string $data ['subject'] 订单标题  必填
     * @param string $data ['body'] 订单详情  可选
     * @return $response 返回app所需字符串
     */
    public function AliPayApp($order_number, $money, $title): string
    {
        $result = Factory::payment()
            ->app()
            ->optional('passback_params', 'app_'.$this->id)
            ->optional('disable_pay_channels', 'credit_group')
            ->pay($title, $order_number, $money);

        return $result->body;
    }

    /**
     * 支付宝根据订单号获取支付结果(异步回调失败时手动调用)
     * author Hso
     */
    public function AliPayGetPayStatus(array $data)
    {
        $aop = new  \AopClient();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->charset = "UTF-8";
        $aop->signType = $this->signType;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->format = 'json';
        $request = new \AlipayTradeQueryRequest ();
        $bizcontent = [];
        if (!empty($data['out_trade_no'])) {
            $bizcontent['out_trade_no'] = $data['out_trade_no'];
        }
        if (!empty($data['trade_no'])) {
            $bizcontent['trade_no'] = $data['trade_no'];
        }
        $bizcontent = json_encode($bizcontent);
        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode;
        return $resultCode;
        if (!empty($resultCode) && $resultCode == 10000) {
            echo "成功";
        } else {
            echo "失败";
        }
    }

    /**
     * 支付宝支付回调签名验证
     * @return bool
     */
    public function AliPayNotifyCheck(): bool
    {
//        \Think\Log::write(var_export($_POST, true), 'INFO', '', C('LOG_PATH').date('y_m_d').'_ali.log');
        $request = app('request')->all();
        return Factory::payment()->common()->verifyNotify($request);
    }
}
